package com.kly.user.task;

import cn.hutool.core.net.NetUtil;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.fqgj.log.factory.LogFactory;
import com.fqgj.log.interfaces.Log;
import com.kly.user.db.dao.UserDao;
import com.kly.user.db.entity.UserEntity;
import com.kly.user.enums.AppEnum;
import com.kly.user.msgClient.MsgAPI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Component
public class MerryChristmasTask {

    private static Log logger = LogFactory.getLog(MerryChristmasTask.class);


    @Autowired
    private UserDao userDao;

    @Resource
    MsgAPI msgAPI;

    @NacosValue(value = "${task.job.executor.ip}", autoRefreshed = true)
    private String taskJobExecutor;

    private String localIP = NetUtil.getLocalhostStr();

    @Scheduled(cron = "0 0 19,21 * * ?")
//    @Scheduled(fixedDelay = 5000)
    public void execute() {

        if (!taskJobExecutor.contains(localIP)) {
            logger.info("=============MerryChristmasTask, currentLocalAddress:{}, onlyExecuteTaskIn:{}", localIP, taskJobExecutor);
            return;
        }

        LocalDate ld = LocalDate.of(2023, 12, 26);
        LocalDateTime endTime = LocalDateTime.of(ld, LocalTime.MAX);
        if (endTime.isAfter(LocalDateTime.now())) {
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.DATE, -20);
            Date date = calendar.getTime();
            int count = userDao.getRegisterDateUserCount(String.valueOf(date.getTime()));
            if (count > 0) {
                int pageSize = (count / 100) + 1;
                for (int i = 0; i < pageSize; i++) {
                    List<UserEntity> userEntityList = userDao.getRegisterDateUserLimit(String.valueOf(date.getTime()), i);
                    for (UserEntity userEntity : userEntityList) {
                        sendMessage(userEntity);
                    }
                    if (userEntityList.size() != 100) {
                        break;
                    }
                }
            }
        }
    }

    private void sendMessage(UserEntity userEntity) {
        msgAPI.sendBackMessage(AppEnum.MEBOO, userEntity.getUserCode(), "\uD83C\uDF84 Find your Christmas sweetheart \uD83C\uDF84", "  On Meboo,capture her, and fulfill all your desires.\uD83D\uDE09 Let desire spread on Christmas night！\uD83D\uDC44\uD83C\uDF46\uD83C\uDF87 ");
    }

}
